package cn.com.lms.business.cozmgt.web;

import cn.com.lms.business.core.constant.ErrorEnum;
import cn.com.lms.business.core.util.SystemUserUtil;
import cn.com.lms.business.course.persistence.entity.CourseCategoryTree;
import cn.com.lms.business.course.persistence.entity.FbCourseInfo;
import cn.com.lms.business.course.service.FbCourseInfoService;
import cn.com.lms.business.cozmgt.persistence.entity.CatalogManage;
import cn.com.lms.business.cozmgt.service.CatalogManageService;
import cn.com.lms.business.user.persistence.entity.SysUserVo;

import com.bnzj.core.exception.BusinessException;
import com.bnzj.core.persistence.query.CompareExpression;
import com.bnzj.core.persistence.query.CompareType;
import com.bnzj.core.persistence.query.IExpression;

import com.bnzj.core.persistence.query.QueryHelpBean;
import com.bnzj.core.persistence.util.EntityUtils;
import com.bnzj.core.rest.ResponseResult;
import com.bnzj.core.rest.ResultCode;

import com.bnzj.core.webmvc.util.WebMvcUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @Author: 16266
 * @DateTime: 2020/3/13 14:13
 * @Description: 目录管理控制器
 */
@Tag(name = "课程管理", description = "目录管理")
@RestController
@RequestMapping(value = "/coz/mgt")
public class CatalogManageController {

    @Autowired
    private CatalogManageService catalogManageService;

    @Autowired
    private FbCourseInfoService fbCourseInfoService;

    @Operation(summary = "目录管理新增", responses = {
            @ApiResponse(responseCode = "1", description = "新增成功", content = @Content(mediaType = "application/json", schema = @Schema(implementation = ResponseResult.class))),
            @ApiResponse(responseCode = "0", description = "新增失败")})
    @PostMapping(value = "/add")
    public ResponseResult<CatalogManage> addCatalogManage(@RequestBody CatalogManage catalogManage) {
        SysUserVo currentUser = SystemUserUtil.getCurrentUser();
        EntityUtils.saveBefore(catalogManage, currentUser.getAccount(), currentUser.getCname());
        catalogManageService.save(catalogManage);
        return ResponseResult.success();
    }

    @Operation(summary = "分页查询目录树", description = "", parameters = {
            @Parameter(name = "offset", description = "起始页", schema = @Schema(name = "offset", description = "", implementation = String.class)),
            @Parameter(name = "limit", description = "页大小", schema = @Schema(name = "limit", description = "", implementation = String.class)),
            @Parameter(name = "keyWord", description = "目录名称进行模糊搜索", schema = @Schema(name = "keyWord", description = "", implementation = String.class)),
            @Parameter(name = "parentId", description = "父目录Id", schema = @Schema(name = "parentId", description = "", implementation = Integer.class))
    })
    @GetMapping(value = "/page")
    public ResponseResult<Page<CatalogManage>> getCatalogManage(HttpServletRequest request) {
        Pageable pageable = WebMvcUtils.initPage(request, Sort.by(Sort.Direction.DESC, "create_time", "sort"));
        QueryHelpBean dicQueryBean = catalogManageService.getQueryHelpBean();
        dicQueryBean.setPageable(pageable);
        //目录名称模糊搜索
        IExpression orCondition1 = CompareExpression.build("d.dir_name", CompareType.like, request.getParameter("keyWord"));
        //默认查询主目录 parent_id为0
        IExpression orCondition2 = CompareExpression.build("d.parent_id", CompareType.equal, request.getParameter("parentId"));
        dicQueryBean.addWhere(orCondition1.and(orCondition2));
        Page<CatalogManage> page = catalogManageService.findAllCatalogManage(dicQueryBean);
        return ResponseResult.success(page);
    }


    @Operation(summary = "更新", responses = {
            @ApiResponse(responseCode = "1", description = "更新成功", content = @Content(mediaType = "application/json", schema = @Schema(implementation = ResponseResult.class))),
            @ApiResponse(responseCode = "0", description = "更新失败")})
    @PostMapping("/update")
    public ResponseResult<?> updateCatalogManage(@RequestBody CatalogManage catalogManage) {
        if (ObjectUtils.isEmpty(catalogManage.getId())) {
            throw new BusinessException(ErrorEnum.RECORD_NOT_EXIST.getMessage(), "" + ErrorEnum.RECORD_NOT_EXIST.getCode());
        }
        SysUserVo currentUser = SystemUserUtil.getCurrentUser();
        catalogManage.setModifyBy(currentUser.getAccount());
        catalogManage.setModifyName(currentUser.getCname());
        catalogManage.setModifyTime(new Date());
        Optional<CatalogManage> catalogManageOpt = catalogManageService.findById(catalogManage.getId());
        if (!catalogManageOpt.isPresent()) {
            throw new BusinessException(ErrorEnum.RECORD_NOT_EXIST.getMessage(), "" + ErrorEnum.RECORD_NOT_EXIST.getCode());
        }
        CatalogManage catalogManageDb = catalogManageOpt.get();
        BeanUtils.copyProperties(catalogManage, catalogManageDb);
        catalogManageService.save(catalogManageDb);
        return ResponseResult.success();
    }


    @Operation(summary = "删除", responses = {
            @ApiResponse(responseCode = "1", description = "删除成功", content = @Content(mediaType = "application/json", schema = @Schema(implementation = ResponseResult.class))),
            @ApiResponse(responseCode = "0", description = "删除失败")})
    @PostMapping(value = "/delete")
    public ResponseResult<?> deleteById(@RequestBody CatalogManage catalogManage) {
        List<FbCourseInfo> courseInfoList  = fbCourseInfoService.findByCategoryId(catalogManage.getId());
        if (CollectionUtils.isEmpty(courseInfoList)) {
            catalogManageService.delete(catalogManage.getId());
            return ResponseResult.success();
        } else {
            return ResponseResult.failure(ResultCode.NOT_ALLOWED_TO_DELETE,"删除错误！请检查目录下是否有课程");
        }
    }

    /*
     * @author liuwei
     * @date 2020/3/16 16:48
     * @desc 获取目录树（带统计课程统计数）
     */
    @Operation(summary = "获取目录树（带统计课程统计数）", description = "获取目录树")
    @GetMapping("/getCategoryTree")
    public ResponseResult<List<CourseCategoryTree>> getCategoryTreeList(HttpServletRequest request) {
        return ResponseResult.success(catalogManageService.getCategoryTreeList(request));
    }


}
